/**
 * 页脚脚本
 */
// 给图片加水印相关代码
if ($('#app_watermark').length === 1) {
  var watermarkInfo = {
    fontSize: 18, // 像素值
    fontFamily: 'cursive',
    content: '',
    color: '#fffbf0',
    offsetX: 0,
    offsetY: 0,
    width: 0,
    height: 0
  };
  (function (watermarkInfo) {
    var img = new Image();
    var canvasInfo = {
      width: 0,
      height: 0
    }
    /**
     * 重置水印
     */
    function resetWatermark() {
      $('#watermark').text('').css({
        top: 0,
        left: 0,
      });
    };
    /**
     * 设置canvas图像到下载链接上
     */
    function setCanvasImgToDownloadLink() {
      var imgData = document.getElementById('target_canvas').toDataURL();
      $('#download_file').attr('href', imgData);
    };
    /**
     * 设置Canvas高度和宽度
     * @param {number} width
     * @param {number} height
     */
    function setCanvasSize(width, height) {
      canvasInfo.width = width;
      canvasInfo.height = height;
      $('#target_canvas').attr('width', width).attr('height', height);
      // 解决图片过大时，在canvas-container不能根据canvas的宽度自动撑宽的问题
      $('#app_watermark').css({
        width: width < 500 ? 500 : width,
      });
    };
    /**
     * 加载图片资源到canvas中
     * @param {File} imgFile
     */
    function setImgIntoCanvas(imgFile) {
      var reader = new FileReader();

      reader.onloadend = function (e) {
        var dataURL = e.target.result;
        img.onload = function (event) {
          var ctx = document.getElementById('target_canvas').getContext('2d');
          //将canvas大小设置为和图片一样大
          setCanvasSize(event.target.naturalWidth, event.target.naturalHeight);
          ctx.drawImage(img, 0, 0);
          setCanvasImgToDownloadLink();
        };
        img.src = dataURL;
      };
      reader.readAsDataURL(imgFile);
      resetWatermark();
    };

    // 设置文本到canvas中
    var setTextIntoCanvas = function () {
      var waterMarkPosition = $('#watermark').offset();
      var x = waterMarkPosition.left - canvasInfo.left;
      var y = waterMarkPosition.top - canvasInfo.top;
      var ctx = document.getElementById('target_canvas').getContext('2d');
      ctx.font = watermarkInfo.fontSize + 'px ' + watermarkInfo.fontFamily;
      ctx.fillStyle = watermarkInfo.color;
      ctx.fillText(watermarkInfo.content, x, y + watermarkInfo.fontSize);
      setCanvasImgToDownloadLink();
    };

    // 绑定移动水印相关事件
    var bindEvent4DragWatermark = function () {
      $('#watermark').on('dragstart', function (e) {
        var ctx = document.getElementById('target_canvas').getContext('2d');
        ctx.clearRect(0, 0, $('#target_canvas').width(), $('#target_canvas').height());
        ctx.drawImage(img, 0, 0);
        // 显示可拖拽水印
        $(this).addClass('selected');
        watermarkInfo.offsetX = e.originalEvent.offsetX + canvasInfo.left;
        watermarkInfo.offsetY = e.originalEvent.offsetY + canvasInfo.top;
      });
      // 让水印跟着鼠标移动
      $('#watermark').on('drag', function (e) {
        var x = e.originalEvent.pageX;
        var y = e.originalEvent.pageY;
        if (x === 0 && y === 0) {
          return;
        }
        x -= watermarkInfo.offsetX;
        y -= watermarkInfo.offsetY;

        $('#watermark').css('left', x).css('top', y);
      });
      $('#watermark').on('dragend', function (e) {
        // 调整位置，使水印无法超出canvas边界
        var x = e.originalEvent.pageX - watermarkInfo.offsetX;
        var y = e.originalEvent.pageY - watermarkInfo.offsetY;
        if (x < 0) {
          x = 0;
        }
        if (y < 0) {
          y = 0;
        }

        var maxX = canvasInfo.width - watermarkInfo.width;
        var maxY = canvasInfo.height - watermarkInfo.height;
        if (x > maxX) {
          x = maxX;
        }
        if (y > maxY) {
          y = maxY;
        }
        $('#watermark').css('left', x).css('top', y);
        // 拖拽完水印，文本隐藏
        $('#watermark').removeClass('selected');
        setTextIntoCanvas();
      });
      // 让鼠标不显示禁用样式
      $('#canvas-container').on('dragover', function (e) {
        e.preventDefault();
      });
    }

    // 绑定事件
    var bindEvent = function () {
      // 按下选择的背景图
      $('#btn_select_file').click(function () {
        $('#target_file').click();
      });
      // 文件改变时获取文件，并文件渲染进canvas
      $('#target_file').change(function (event) {
        var imgFile = event.target.files[0];
        setImgIntoCanvas(imgFile);
      });
      //设置水印
      $('#btn_set_watermark').click(function () {
        watermarkInfo.content = $('#watermark_content').val();
        $('#watermark').text(watermarkInfo.content).show();
        watermarkInfo.height = $('#watermark').height();
        watermarkInfo.width = $('#watermark').width();
        setTextIntoCanvas();
      });

      bindEvent4DragWatermark();
    };
    // 此处通过这种方式将html插入，是因为博客园自动屏蔽了canvas标签和download属性
    var initHtmlConstruct = function () {
      $('#canvas-container').text('').append('<canvas id="target_canvas" width="100" height="100">浏览器不支持此功能，请升级</canvas><span draggable="true" id="watermark"></span>')
      $('#toolbar').append('<a class="btn" id="download_file" href="#" download="水印图片">下载合成图片</a>');
      $('#watermark_content').attr('placeholder', '请输入水印文字');
    }
    // 初始化水印设置
    var initWatermark = function () {
      $('#watermark').css({
        fontSize: watermarkInfo.fontSize + 'px',
      });
    }
    // 初始化canvas信息
    var initCanvasInfo = function () {
      var $targetCanvas = $('#target_canvas');
      if ($targetCanvas.length === 1) {
        var canvasPosition = $targetCanvas.offset()
        canvasInfo.left = canvasPosition.left;
        canvasInfo.top = canvasPosition.top;
        canvasInfo.width = $targetCanvas.width();
        canvasInfo.height = $targetCanvas.height();
      }
    }
    $(function () {
      if ($('#app_watermark').length === 1) {
        initHtmlConstruct();
        initWatermark();
        initCanvasInfo();
        bindEvent();
        $(window).resize(function () {
          // 窗口大小调整后canvas位置发生改变
          initCanvasInfo();
        });
      }
    })
  })(watermarkInfo);
}
// 图片背景透明化相关代码
if ($('#app_transparent_img').length === 1) {
  var recoverSize = 20;
  var transparentConfig = {
    colorDiff: 20,
    setRecoverSize: function (value) {
      recoverSize = value;
      $('#recover_img').css({
        width: value,
        height: value
      })
    }
  };
  (function () {
    var img = new Image();
    var isRecoverMode = false;
    var canvasInfo = {
      width: 0,
      height: 0
    }
    var imgDataArr = []
    var resultImgDataArr = []

    /**
     * 将canvas某块区域设置为透明
     */
    function setTransparent(ctx, x, y, width, height) {
      ctx.putImageData(ctx.createImageData(width, height), x, y);
    }
    /**
     * 设置canvas图像到下载链接上
     */
    function setCanvasImgToDownloadLink() {
      var imgData = document.getElementById('target_canvas').toDataURL();
      $('#download_file').attr('href', imgData);
    };
    /**
     * 获取图像数据中指定偏移处的颜色信息
     */
    function getColorInfo(imgDataArr, offsetX, offsetY) {
      var pos = canvasInfo.width * 4 * offsetY + offsetX * 4;
      return {
        rValue: imgDataArr[pos],
        gValue: imgDataArr[pos + 1],
        bValue: imgDataArr[pos + 2],
        aValue: imgDataArr[pos + 3]
      }
    }
    /**
     * 获取图像数据指定位置颜色与指定颜色的色差
     */
    function getColorDiff(imgDataArr, pos, colorInfo) {
      var value = Math.pow(imgDataArr[pos] - colorInfo.rValue, 2) +
        Math.pow(imgDataArr[pos + 1] - colorInfo.gValue, 2) +
        Math.pow(imgDataArr[pos + 2] - colorInfo.bValue, 2);

      return Math.pow(value, 0.5);
    }
    /**
     * 设置图像数据指定位置为透明色
     */
    function setTransparent(imgDataArr, pos) {
      imgDataArr[pos] = 0;
      imgDataArr[pos + 1] = 0;
      imgDataArr[pos + 2] = 0;
      imgDataArr[pos + 3] = 0;
    }
    /**
     * 非恢复模式下，点击canvas，以点击处颜色为标准，去掉颜色色差在指定色差范围内的颜色
     */
    function transparetModeCanvasClick(e) {
      if (imgDataArr.length === 0) {
        return;
      }
      if (resultImgDataArr.length === 0) {
        resultImgDataArr = imgDataArr.slice(0)
      }
      var clickColorInfo = getColorInfo(resultImgDataArr, e.offsetX, e.offsetY)

      // 如果是透明颜色则不做处理
      if (clickColorInfo.aValue === 0) {
        return;
      }
      var ctx = document.getElementById('target_canvas').getContext('2d');
      for (var pos = 0, len = canvasInfo.width * canvasInfo.height * 4; pos < len; pos = pos + 4) {
        if (getColorDiff(resultImgDataArr, pos, clickColorInfo) < transparentConfig.colorDiff) {
          setTransparent(resultImgDataArr, pos);
        }
      }
      ctx.putImageData(new ImageData(resultImgDataArr, canvasInfo.width, canvasInfo.height), 0, 0);
      setCanvasImgToDownloadLink();
    }
    // 根据鼠标的偏移位置获取recover_img位置
    function getRecoverImgPos(e) {
      // 给鼠标位置+1，是为了让recover_img不会出现在鼠标下方，从而使得鼠标点击时不会点击在recover_img上
      return {
        x: e.offsetX + 1,
        y: e.offsetY + 1
      }
    }

    var timerHandler = 0
    /**
     * 恢复模式下，鼠标在canvas上移动，呈现原先图像
     */
    function recoverModeCanvasMove(e) {
      if (imgDataArr.length === 0) {
        return;
      }
      var $recoverImg = $("#recover_img");
      var recoverImgPos = getRecoverImgPos(e)
      if (recoverImgPos.x > canvasInfo.width - recoverSize || recoverImgPos.y > canvasInfo.height - recoverSize) {
        $recoverImg.hide();
        return;
      } else {
        $recoverImg.show();
      }
      $recoverImg.css({
        transform: 'translate(' + recoverImgPos.x + 'px,' + recoverImgPos.y + 'px)',
        'background-position': (-recoverImgPos.x - 1) + 'px ' + (-recoverImgPos.y - 1) + 'px'
      });

    }

    /**
     * 恢复模式下，点击canvas，将点击处指定范围内图像恢复原样
     */
    function recoverModeCanvasClick(e) {
      if (imgDataArr.length === 0) {
        return;
      }
      var recoverImgPos = getRecoverImgPos(e);
      for (var i = 0, ylen = recoverSize; i < ylen; i++) {
        var pos = canvasInfo.width * 4 * (recoverImgPos.y + i) + recoverImgPos.x * 4;
        for (var j = pos, xlen = pos + recoverSize * 4; j < xlen; j++) {
          resultImgDataArr[j] = imgDataArr[j]
        }
      }
      var ctx = document.getElementById('target_canvas').getContext('2d');
      ctx.putImageData(new ImageData(resultImgDataArr, canvasInfo.width, canvasInfo.height), 0, 0);
      setCanvasImgToDownloadLink()
    }

    /**
     * 设置Canvas高度和宽度
     * @param {number} width
     * @param {number} height
     */
    function setCanvasSize(width, height) {
      canvasInfo.width = width;
      canvasInfo.height = height;
      $('#target_canvas').attr('width', width).attr('height', height);
      // 解决图片过大时，在canvas-container不能根据canvas的宽度自动撑宽的问题
      $('#app_transparent_img').css({
        width: width < 500 ? 500 : width,
      });
    };
    /**
     * 加载图片资源到canvas中
     * @param {File} imgFile
     */
    function setImgIntoCanvas(imgFile) {
      var reader = new FileReader();

      reader.onloadend = function (e) {
        var dataURL = e.target.result;
        img.onload = function (event) {
          var ctx = document.getElementById('target_canvas').getContext('2d');
          //将canvas大小设置为和图片一样大
          var imgWidth = event.target.naturalWidth,
            imgHeight = event.target.naturalHeight;
          setCanvasSize(imgWidth, imgHeight);
          ctx.drawImage(img, 0, 0);

          imgDataArr = ctx.getImageData(0, 0, imgWidth, imgHeight).data;
          resultImgDataArr = imgDataArr.slice(0);
          setCanvasImgToDownloadLink();
        };
        img.src = dataURL;
        $('#recover_img').css("background-image", "url(" + dataURL + ")");
      };
      reader.readAsDataURL(imgFile);
    }

    // 绑定事件
    var bindEvent = function () {
      // 按下选择的背景图
      $('#btn_select_file').click(function () {
        $('#target_file').click();
      });
      // 文件改变时获取文件，并文件渲染进canvas
      $('#target_file').change(function (event) {
        var imgFile = event.target.files[0];
        setImgIntoCanvas(imgFile);
      });
      // 开启恢复模式
      $('#btn_recover').click(function () {
        var $targetCanvas = $('#target_canvas');
        $targetCanvas.off("click").off("mousemove").removeClass('recover-mode');

        isRecoverMode = !isRecoverMode
        if (isRecoverMode) {
          $("#recover_img").css({
            width: recoverSize,
            height: recoverSize
          });
          $targetCanvas.addClass('recover-mode').click(recoverModeCanvasClick).mousemove(recoverModeCanvasMove).mouseleave(function () {
            $("#recover_img").hide();
          });
          $('#btn_recover').text('关闭恢复模式')
        } else {
          $targetCanvas.click(transparetModeCanvasClick);
          $("#recover_img").hide();
          $('#btn_recover').text('开启恢复模式')
        }
      })
    };


    // 此处通过这种方式将html插入，是因为博客园自动屏蔽了canvas标签和download属性
    var initHtmlConstruct = function () {
      var $container = $('#canvas-container');
      // 加入处理图片的canvas
      $container.text('').append('<canvas id="target_canvas" width="100" height="100">浏览器不支持此功能，请升级</canvas>')
      // 处理recover模式下的跟随鼠标的图像
      $container.append('<div id="recover_img"></div>')
      $('#toolbar').append('<a class="btn" id="download_file" href="#" download="透明化图片">下载合成图片</a>');
    }
    // 初始化canvas信息
    var initCanvasInfo = function () {
      var $targetCanvas = $('#target_canvas');
      if ($targetCanvas.length === 1) {
        var canvasPosition = $targetCanvas.offset()
        canvasInfo.width = $targetCanvas.width();
        canvasInfo.height = $targetCanvas.height();
      }
      //点击canvas，以点击处颜色为标准，去掉颜色色差在指定色差范围内的颜色
      $targetCanvas.off("click").click(transparetModeCanvasClick)
    }
    $(function () {
      if ($('#app_transparent_img').length === 1) {
        initHtmlConstruct();
        initCanvasInfo();
        bindEvent();
        $(window).resize(function () {
          // 窗口大小调整后canvas位置发生改变
          initCanvasInfo();
        });
      }
    })
  })();
}